<template>
  <div id="costAbnormalList">
    <div>
      <el-form :inline="true" :model="formdata" class="demo-form-inline" label-width="71px">
        <el-form-item label="所属区域">
          <el-select v-model="formdata.customer_area_id" filterable placeholder="所属区域" style="width: 200px; padding: 0px 8px 0px 0px">
            <el-option v-for="(item, index) in websiteList" :key="index" :value="item.id+''" :label="item.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="运单号">
          <el-input v-model="formdata.waybill_no" placeholder="运单号" style="width: 110%;"></el-input>
        </el-form-item>
        <el-form-item label="周">
          <el-date-picker v-model="formdata.create_iso_week" type="week" format="yyyy年WW周" placeholder="选择周"></el-date-picker>
          </el-date-picker>
        </el-form-item>
        <el-form-item label="月">
          <el-date-picker v-model="formdata.create_month" type="month" placeholder="选择月">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="运单总费用" label-width="90px">
            <el-input v-model="formdata.total_freight.min_cost" style="width: 100px;" placeholder="最小费用"></el-input> -- <el-input v-model="formdata.total_freight.max_cost" placeholder="最大费用" style="width: 100px;"></el-input>
        </el-form-item>
        <el-form-item label="" style="margin: 0px 0px 15px 0px;">
          <el-button type="primary" @click="Objquality_operationObj()">查询</el-button>
          <el-button type="primary" @click="replacement()">重置</el-button>
          <el-button type="primary" @click="Derivement()">导出</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div>
      <el-table :data="tableData" style="width: 100%" border>
        <el-table-column prop="waybill_no" label="运单号" width="160" />
        <el-table-column prop="loss" label="亏损" width="90">
          <template slot-scope="scope">
            <el-tag type="danger"> {{scope.row.loss}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="customer_name" label="所属客户" width="180" />
        <el-table-column prop="customer_area_name" label="客户区域" width="160" />
        <el-table-column prop="g_total_money" label="干线总运费" width="120" />
        <el-table-column prop="hd_total_money" label="回单总运费" width="120" />
        <el-table-column prop="hx_total_money" label="回箱总运费" width="120" />
        <el-table-column prop="l_total_money" label="揽收总运费" width="120" />
        <el-table-column prop="p_total_money" label="配送总运费" width="120" />
        <el-table-column prop="total_freight" label="运单总费用" width="120" />
        <el-table-column prop="cost_overruns_reason" label="成本超出原因" width="120" />
        <el-table-column prop="waybill_product_type_name" label="承运类型" width="120" />
        <el-table-column prop="original_address" label="起始地" width="180" />
        <el-table-column prop="destination_address" label="目的地" width="180" />
        <el-table-column prop="incubators" label="保温箱类型/数量" width="180">
          <template slot-scope="scope">
            <el-tag v-for="item in scope.row.incubators">{{item.package_type}}/{{item.package_quantity}}个</el-tag>
            <!-- <el-tag v-for="item in scope.row.incubators">{{item.package_quantity}}个</el-tag> -->
          </template>
        </el-table-column>
        <el-table-column prop="create_iso_week" label="周" width="80" />
        <el-table-column prop="create_month" label="月" width="80" />
      </el-table>
      <div style="display: flex; justify-content: flex-end;margin: 10px 0px 0px 0px;">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage4" :page-sizes="[10, 20, 30, 40]" :page-size="100" layout="total, sizes, prev, pager, next, jumper" :total="totalData">
        </el-pagination>
      </div>
    </div>
  </div>
</template>
<script>
import {
  branchList, quality_operation_reminder_cost_abnormal_list, quality_operation_reminder_export
} from "@/api/Largewidthmeterlist";
export default {
  name: "costAbnormalList",
  data() {
    return {
      formdata: {
        customer_area_id: "",
        waybill_no: "",
        create_year: "",
        create_month: "",
        create_iso_week: "",
        create_time: {
          start_time: "",
          end_time: ""
        },
        page: "1",
        page_size: "10",
        total_freight: {
          max_cost: "",
          min_cost: "",
        }
      },
      websiteList: [],
      tableData: [],
      qualityway: '',
      currentPage4: 1,
      totalData: 0
    }
  },
  mounted() {
    this.getWebsiteList();
    if (this.$route.query) {
      if (this.$route.query.customer_area_id) {
        this.formdata.customer_area_id = this.$route.query.customer_area_id + ''
        this.qualityway = this.$route.query.way
        if (this.$route.query.way == 1) {
          this.formdata.create_month = this.convertToDate(this.$route.query.label)
        } else if (this.$route.query.way == 2) {
          this.formdata.create_iso_week = "Sun Nov 05 2023 16:00:00 GMT+0000"

        }
      }
      this.quality_operationObj()
    } else {
      this.quality_operationObj()
    }
  },
  methods: {
    async getWebsiteList() {
      let result = await branchList({ branch_type: "3", is_head: '1' });
      this.websiteList = result.data;
    },
    Objquality_operationObj() {
      this.formdata.page = "1"
      this.formdata.page_size = "10"
      this.quality_operationObj()
    },

    quality_operationObj() {
      var formattedWeek = ""
      var formamonth = ""
      if (this.formdata.create_iso_week != '') {
        const inputDate = new Date(this.formdata.create_iso_week);
        const year = inputDate.getFullYear();
        const weekNumber = this.getISOWeek(inputDate);
        formattedWeek = `${year}${weekNumber.toString().padStart(2, '0')}`;
      }
      if (this.formdata.create_month != '') {
        const inputDate = new Date(this.formdata.create_month);
        const year = inputDate.getFullYear();
        const month = (inputDate.getMonth() + 1).toString().padStart(2, '0');
        formamonth = `${year}${month}`;
      }
      var param = {
        ...this.formdata,
        create_iso_week: formattedWeek,
        create_month: formamonth,
        total_freight: {
          max_cost: this.formdata.total_freight.max_cost,
          min_cost: this.formdata.total_freight.min_cost
        },
        page: this.formdata.page * 1,
        page_size: this.formdata.page_size * 1,
      }
      quality_operation_reminder_cost_abnormal_list(param).then((res) => {
        this.tableData = res.data.data
        this.totalData = res.data.pagination.total
        this.currentPage4 = res.data.pagination.current_page
      })
    },
    getISOWeek(date) {
      const startOfYear = new Date(date.getFullYear(), 0, 1);
      const days = Math.floor((date - startOfYear) / (24 * 60 * 60 * 1000));
      return Math.ceil((days + startOfYear.getDay() + 1) / 7);
    },
    convertToDate(dateString) {

      const year = parseInt(dateString.substring(0, 4));
      const month = parseInt(dateString.substring(4));
      const dateObject = new Date(year, month - 1); // Note: Months are 
      return dateObject;
    },
    convertToDateWithWeek(weekNumber) {
      // 获取当前年的第一天
      const firstDayOfYear = new Date(new Date().getFullYear(), 0, 1);

      // 计算给定周数的起始日期
      const startDate = new Date(firstDayOfYear.setDate(firstDayOfYear.getDate() + (weekNumber - 1) * 7));

      // 格式化日期为 "Mon Nov 06 2023 00:00:00 GMT+0800" 格式
      const formattedResult = startDate.toUTCString();

      return formattedResult;
    },
    replacement() {
      this.currentPage4 = 1
      Object.assign(this.$data.formdata, this.$options.data().formdata);
      this.quality_operationObj()
    },
    handleSizeChange(val) {
      this.formdata.page_size = val
      this.quality_operationObj()
      // console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.formdata.page = val
      this.quality_operationObj()
      // console.log(`当前页: ${val}`);
    },
    Derivement() {
      var formattedWeek = ""
      var formamonth = ""
      if (this.formdata.create_iso_week != '') {
        const inputDate = new Date(this.formdata.create_iso_week);
        const year = inputDate.getFullYear();
        const weekNumber = this.getISOWeek(inputDate);
        formattedWeek = `${year}${weekNumber.toString().padStart(2, '0')}`;
      }
      if (this.formdata.create_month != '') {
        const inputDate = new Date(this.formdata.create_month);
        const year = inputDate.getFullYear();
        const month = (inputDate.getMonth() + 1).toString().padStart(2, '0');
        formamonth = `${year}${month}`;
      }
      var param = {
        ...this.formdata,
        create_iso_week: formattedWeek,
        create_month: formamonth,
        total_freight: {
          max_cost: this.formdata.total_freight.max_cost,
          min_cost: this.formdata.total_freight.min_cost
        },
        page: 0 * 1,
        page_size: 0 * 1,
      }
      quality_operation_reminder_export(param).then((res) => {
        const linkurl = "https://" + res.data.loaded_url;
        window.open(linkurl, "_blank");
      })
    },

    quality_operationObj() {
      var formattedWeek = "";
      var formamonth = "";
      if (this.formdata.create_iso_week != "") {
        const inputDate = new Date(this.formdata.create_iso_week);
        const year = inputDate.getFullYear();
        const weekNumber = this.getISOWeek(inputDate);
        formattedWeek = `${year}${weekNumber.toString().padStart(2, "0")}`;
      }
      if (this.formdata.create_month != "") {
        const inputDate = new Date(this.formdata.create_month);
        const year = inputDate.getFullYear();
        const month = (inputDate.getMonth() + 1).toString().padStart(2, "0");
        formamonth = `${year}${month}`;
      }
      var param = {
        ...this.formdata,
        create_iso_week: formattedWeek,
        create_month: formamonth,
        page: this.formdata.page * 1,
        page_size: this.formdata.page_size * 1,
      };
      quality_operation_reminder_cost_abnormal_list(param).then((res) => {
        this.tableData = res.data.data;
        if (this.tableData.length > 7) {
          //两排操作栏
          this.maxheight = document.documentElement.clientHeight - 255;
        } else {
          this.maxheight = "auto";
        }
        this.totalData = res.data.pagination.total;
        this.currentPage4 = res.data.pagination.current_page;
      });
    },
    getISOWeek(date) {
      const startOfYear = new Date(date.getFullYear(), 0, 1);
      const days = Math.floor((date - startOfYear) / (24 * 60 * 60 * 1000));
      return Math.ceil((days + startOfYear.getDay() + 1) / 7);
    },
    convertToDate(dateString) {
      const year = parseInt(dateString.substring(0, 4));
      const month = parseInt(dateString.substring(4));
      const dateObject = new Date(year, month - 1); // Note: Months are
      return dateObject;
    },
    convertToDateWithWeek(weekNumber) {
      // 获取当前年的第一天
      const firstDayOfYear = new Date(new Date().getFullYear(), 0, 1);

      // 计算给定周数的起始日期
      const startDate = new Date(
        firstDayOfYear.setDate(firstDayOfYear.getDate() + (weekNumber - 1) * 7)
      );

      // 格式化日期为 "Mon Nov 06 2023 00:00:00 GMT+0800" 格式
      const formattedResult = startDate.toUTCString();

      return formattedResult;
    },
    replacement() {
      this.currentPage4 = 1;
      Object.assign(this.$data.formdata, this.$options.data().formdata);
      this.quality_operationObj();
    },
    handleSizeChange(val) {
      this.formdata.page_size = val;
      this.quality_operationObj();
      // // console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.formdata.page = val;
      this.quality_operationObj();
      // // console.log(`当前页: ${val}`);
    },
  },
};
</script>
<style scoped lang="less">
#costAbnormalList {
  /* width: 100%; */
  background: #ffffff;
  margin: 5px 0px 0px 5px;
  padding: 10px;
}
</style>